package coder.nav.model.vo;

import cn.hutool.core.bean.BeanUtil;
import coder.nav.model.bo.NavTaskBO;
import coder.nav.schedule.action.NavTaskBaseAction;
import coder.nav.service.NavTaskService;
import coder.nav.utils.FileUtils;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Data
public class NavTaskVO implements Serializable {

    @ApiModelProperty("id")
    private Long id;

    @ApiModelProperty("用户id")
    private Long userId;

    @ApiModelProperty("标题")
    private String title;

    @ApiModelProperty("内容")
    private String context;

    @ApiModelProperty("排序（数字越大排序越靠前）")
    private Integer sort;

    @ApiModelProperty("工作日")
    private Integer work;

    @ApiModelProperty("年")
    private Integer year;

    @ApiModelProperty("月")
    private Integer month;

    @ApiModelProperty("日")
    private Integer day;

    @ApiModelProperty("时")
    private Integer hour;

    @ApiModelProperty("分")
    private Integer minute;

    @ApiModelProperty("星期")
    private String weeks;

    @ApiModelProperty("执行时间")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm", timezone = "GMT+8")
    private Date actionTime;

    @ApiModelProperty("执行方法（类名）")
    private String actionFunction;

    @ApiModelProperty("执行方法（描述）")
    public String getActionFunctionDesc() {
        Map<String, NavTaskBaseAction> map = NavTaskService.getTaskFunctionMap();
        String baseBeanName = FileUtils.lowerCaseName(this.getActionFunction());
        NavTaskBaseAction action = map.get(baseBeanName);
        if(Objects.isNull(action)) {
            return "";
        }
        return action.title();
    }

    @ApiModelProperty("执行时间（下次）")
    public String getNextActionTime() {
        NavTaskBO bo = BeanUtil.copyProperties(this, NavTaskBO.class);
        if(Objects.isNull(bo.getActionTime())) {
            return "无符合执行时间";
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        StringBuilder sb = new StringBuilder();
        sb.append("第 1 次执行时间: ").append(sdf.format(bo.getActionTime())).append("\n");
        for(int i = 0; i < 2; i++) {
            Date actionTime = NavTaskService.getNextActionTime(bo, 1);
            if(Objects.isNull(actionTime)) {
                return "无符合执行时间";
            }
            bo.setActionTime(actionTime);
            sb.append("第 ").append(i + 2).append(" 次执行时间: ").append(sdf.format(actionTime)).append("\n");
        }
        return sb.toString();
    }

}
